<template>
    <div style="display: flex; flex-direction: column;">
      <div
        id="chat-input"
        contenteditable="true"
        class="input-section chat-input"
        @paste="inputPaste"
      />
    </div>
  </template>
  
  <script>
  import { md5ValueSalt } from '@/utils/decrypt'
  export default {
    name: 'FileUpload',
    data() {
      return {
        content: '',
        url: null,
        tmpObj: {},
        // 输入的列表 type1表示文本、2表示文件
        inputSection: [
          {
            type: 1,
            value: ''
          },
          {
            type: 2,
            value: null // file
          }
        ]
      }
    },
    mounted() {
      const div = document.getElementById('chat-input')
      const that = this
      div.addEventListener('keydown', function(e) {
        if (e.key === 'Enter' && e.code === 'Enter') {
          // 回车
          if (e.altKey) {
            // alt+enter， 加入换行
            document.execCommand('insertLineBreak')
          } else {
            e.preventDefault()
            // 发送
            that.sendAction()
          }
        }
      })
    },
    methods: {
  
      sendAction() {
        const div = document.getElementById('chat-input')
        // const child = div.childNodes
        this.inputSection = []
        this.deepFindNodes(div)
        // console.log(this.inputSection)
        // 对inputSection分组，相邻的text结合在一起
        const tmpList = []
        var nextObj = null
        for (let i = 0; i < this.inputSection.length; i++) {
          if (i === 0) {
            nextObj = { ...this.inputSection[i] }
          } else {
            if (this.inputSection[i].type === 1 && nextObj.type === this.inputSection[i].type) {
              // 相同id 并且都是text
              nextObj.value = nextObj.value + this.inputSection[i].value
            } else {
              // 非相同id、或者是img、需要分开的
              tmpList.push(nextObj)
              nextObj = { ...this.inputSection[i] }
            }
          }
        }
        if (nextObj) {
          tmpList.push(nextObj)
        }
        // console.log(this.inputSection)
        // console.log(tmpList)
        // 传递inputSection, 之后清空
        this.$emit('send', tmpList)
        this.clearInput()
      },
  
      clearInput() {
        this.inputSection = []
        this.tmpObj = {}
        const div = document.getElementById('chat-input')
        div.innerHTML = ''
      },
  
      // 递归查node值
      deepFindNodes(node) {
        if (!node || node.childNodes.length === 0) {
          return
        }
        const child = node.childNodes
        for (let i = 0; i < child.length; i++) {
          const item = child[i]
          if (item.nodeType === 1) {
            // 节点
            const tagName = item.tagName.toLowerCase()
            if (tagName === 'div') {
              this.deepFindNodes(item)
            } else if (tagName === 'br') {
              // 换行符
              const textObj = {
                type: 1,
                value: '\n'
              }
              this.inputSection.push(textObj)
            } else if (tagName === 'img') {
              // 图片
              console.log(item.id)
              if (this.tmpObj && this.tmpObj[item.id]) {
                // 存在临时对象
                const imgObj = {
                  type: 2,
                  value: this.tmpObj[item.id]
                }
                this.inputSection.push(imgObj)
              }
            } else {
              this.deepFindNodes(item)
            }
          } else if (item.nodeType === Node.TEXT_NODE) {
            // 文本
            const value = item.textContent
            if (value.length === 0) {
              // 空文本
              continue
            }
            const textObj = {
              type: 1,
              value: item.textContent
            }
            this.inputSection.push(textObj)
          } else {
            // 其它的
            this.deepFindNodes(item)
          }
        }
      },
  
      async inputPaste(event) {
        try {
          event.preventDefault()
          const data = event.clipboardData || window.clipboardData
          if (data.items.length === 0) {
            return
          }
          const item = data.items[0]
          if (item.kind === 'string') {
            item.getAsString(val => {
              document.execCommand('insertText', false, val)
            })
            // console.log(str)
          } else if (item.type.includes('image')) {
            const imgFile = await item.getAsFile()
            console.log(imgFile)
            const imgId = md5ValueSalt(imgFile.name, Date.now())
            const reader = new FileReader()
            reader.onload = (e) => {
              // console.log(reader.result)
              this.url = reader.result
              const blob = new Blob([e.target.result], { type: imgFile.type })
              // this.content = reader.result
              // document.execCommand('insertImage', false, this.url)
              this.insertImageNode(blob, imgId)
              this.tmpObj[imgId] = imgFile
              // 保存一下
            }
            reader.readAsArrayBuffer(imgFile)
          } else { // 文件等。。。
            console.log(item)
          }
        } catch (err) {
          console.log(err)
        }
      },
  
      insertTextNode(text) {
        const div = document.getElementById('chat-input')
        var sel = window.getSelection()
        console.log(sel)
        if (sel.getRangeAt && sel.rangeCount) {
          var range = sel.getRangeAt(0)
          var span = document.createElement('span')
          span.value = text
          range.insertNode(span)
          div.focus()
        }
      },
  
      // 插入图片
      insertImageNode(blob, imgId) {
        // const div = document.getElementById('chat-input')
        var sel = window.getSelection()
        console.log(sel)
        if (sel.getRangeAt && sel.rangeCount) {
          var range = sel.getRangeAt(0)
          range.deleteContents()
  
          var img = document.createElement('img')
          img.src = window.URL.createObjectURL(blob)
          img.id = imgId
  
          var imgContainer = document.createElement('div')
          imgContainer.appendChild(img)
          range.insertNode(imgContainer)
          sel.collapseToEnd()
        }
      }
  
      // handlePaste(value) {
      //   console.log(value)
      //   const item = value.clipboardData.items[0]
      //   console.log(item)
      //   if (item.kind === 'string') {
      //     this.pasteTextPlain(item)
      //   } else if (item.kind === 'file') {
      //     // 粘贴文件
      //     if (item.type.includes('image')) {
      //       // 粘贴图片
      //       const imgFile = item.getAsFile()
      //       console.log(imgFile)
      //       const reader = new FileReader()
      //       reader.onload = () => {
      //         console.log(reader.result)
      //         this.url = reader.result
      //         // this.content = reader.result
      //       }
      //       reader.readAsDataURL(imgFile)
      //     }
      //   }
      // },
  
      // // 纯文本粘贴
      // pasteTextPlain(item) {
      //   item.getAsString(val => {
      //     // this.content = this.content + val
      //     const pos = this.textAreaPosition()
      //     this.content = this.content.slice(0, pos) + val + this.content.slice(pos)
  
      //     const ele = document.getElementById('myInput')
      //     const nextPos = pos + val.length
      //     this.$nextTick(() => {
      //       ele.setSelectionRange(nextPos, nextPos)
      //     })
      //   })
      // },
  
      // // 获取光标位置
      // textAreaPosition() {
      //   var pos = 0
      //   const ele = document.getElementById('myInput')
      //   if (ele.selectionStart) {
      //     pos = ele.selectionStart
      //   }
      //   return pos
      // },
  
      // sendClick(e) {
      //   console.log(e)
      // },
  
      // handleFileChange(e) {
      //   const file = e.target.files
      //   const item = file[0]
      //   console.log(item)
  
      //   uploadFile(item).then(val => {
      //     console.log(val)
      //     const url = val.host + '/' + val.path
      //     this.url = url
      //   })
      // }
    }
  }
  </script>
  <style lang="scss" scoped>
  
  .input-section {
    width: 100%;
    height: 100%;
    // border: 1px solid #eee;
    // border-radius: 10px;
    padding: 15px;
    overflow: auto;
  }
  
  .chat-input {
    ::v-deep img {
      max-width: 100px;
    }
  }
  </style>
  